<template>
  <div class="activity-post-editor" style="position:relative;">
    <!-- 文本输入区域 -->
    <textarea v-model="content" placeholder="说点什么..." class="editor-textarea"></textarea>

    <!-- 话题选择器 -->
    <div class="topic-selector" style="margin-bottom: 12px; display: flex; align-items: center; gap: 10px;">
      <button class="black-btn" style="width: 100px; padding: 8px 0; margin-bottom: 0;" @click="showNewTopicModal = true">新建话题</button>
      <select v-model="selectedTopicId" class="topic-select">
        <option value="" disabled selected>请选择话题</option>
        <option v-for="topic in topics" :key="topic.id" :value="topic.id">
          {{ topic.content }}
        </option>
      </select>
    </div>

    <!-- 媒体上传与可见性设置 -->
    <div class="row-flex">
      <!-- 媒体上传按钮 -->
      <div class="media-upload-plus" @click="triggerFileInput">
        <span class="plus-icon">+</span>
        <input type="file" ref="fileInput" multiple accept="image/*,video/*" @change="handleFileUpload" style="display:none" />
      </div>

      <!-- 可见性选择器 -->
      <div class="visibility-selector">
        <div class="selected-visibility" @click="toggleVisibilityMenu">
          <i :class="visibilityIcon"></i>
          <span>{{ visibilityText }}</span>
          <i class="fas fa-chevron-down"></i>
        </div>
        <div class="visibility-menu" v-show="showVisibilityMenu">
          <div
            class="visibility-option"
            v-for="option in visibilityOptions"
            :key="option.value"
            @click="selectVisibility(option.value)"
            :class="{ active: visibility === option.value }"
          >
            <i :class="option.icon"></i>
            {{ option.label }}
          </div>
        </div>
      </div>
    </div>

    <!-- 媒体预览区域 -->
    <div
      class="media-preview"
      ref="mediaPreview"
    >
      <div v-for="(media, idx) in mediaList" :key="idx" class="media-thumb">
        <img v-if="media.type==='image'" :src="media.preview" />
        <video v-else controls :src="media.preview" />
        <button class="black-btn remove-btn" @click="removeMedia(idx)">移除</button>
      </div>
    </div>

    <!-- 发布按钮 -->
    <button class="black-btn publish-btn-bottom" @click="submitEdit" :disabled="isLoading">{{ isLoading ? '保存中...' : '保存修改' }}</button>

    <!-- 新建话题弹窗 -->
    <div v-if="showNewTopicModal" class="new-topic-modal">
      <button class="close-modal-btn" @click="showNewTopicModal = false">退出新建话题</button>
      <input v-model="newTopicContent" placeholder="输入新话题..." class="topic-input" />
      <button class="black-btn" style="margin-top:18px;" @click="createTopic" :disabled="isCreatingTopic">{{ isCreatingTopic ? '创建中...' : '确定' }}</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import axios from 'axios';

/**
 * 定义组件的 props
 */
const props = defineProps({
  activity: { type: Object, required: true }
});

/**
 * 定义组件的 emits
 */
const emit = defineEmits(['success', 'close']);

/**
 * 编辑器文本内容
 */
const content = ref(props.activity.content || '');

/**
 * 当前可见性设置
 */
const visibility = ref(props.activity.visibility ?? 0);

/**
 * 已上传媒体列表，格式为 { file, preview, type }
 */
const mediaList = ref([]);

/**
 * 是否正在提交数据
 */
const isLoading = ref(false);

/**
 * 文件输入框引用
 */
const fileInput = ref(null);

/**
 * 是否显示可见性菜单
 */
const showVisibilityMenu = ref(false);

/**
 * 话题列表
 */
const topics = ref([]);

/**
 * 当前选中的话题 ID
 */
const selectedTopicId = ref(props.activity.topicId || '');

/**
 * 是否显示新建话题弹窗
 */
const showNewTopicModal = ref(false);

/**
 * 新建话题的内容
 */
const newTopicContent = ref('');

/**
 * 是否正在创建话题
 */
const isCreatingTopic = ref(false);

/**
 * 媒体预览区域的 DOM 引用
 */
const mediaPreview = ref(null);

/**
 * 可见性选项配置
 */
const visibilityOptions = [
  { value: 0, label: '所有人可见', icon: 'fas fa-globe' },
  { value: 1, label: '好友可见', icon: 'fas fa-user-friends' },
  { value: 2, label: '仅自己可见', icon: 'fas fa-lock' }
];

/**
 * 计算当前可见性文本
 */
const visibilityText = computed(() => {
  return visibilityOptions.find(o => o.value === visibility.value)?.label || '';
});

/**
 * 计算当前可见性图标
 */
const visibilityIcon = computed(() => {
  return visibilityOptions.find(o => o.value === visibility.value)?.icon || '';
});

/**
 * 初始化媒体列表，从 activity.mediaUrls 解析已有媒体
 */
if (props.activity.mediaUrls) {
  try {
    const arr = Array.isArray(props.activity.mediaUrls) ? props.activity.mediaUrls : JSON.parse(props.activity.mediaUrls);
    arr.forEach(url => {
      mediaList.value.push({ preview: url, type: url.match(/\.(mp4|webm|ogg)$/i) ? 'video' : 'image', file: null });
    });
  } catch (e) { /* empty */ }
}

/**
 * 组件挂载时获取话题列表
 */
onMounted(async () => {
  try {
    const response = await axios.get('http://localhost:8085/topics');
    topics.value = response.data;
  } catch (e) {
    topics.value = [];
  }
});

/**
 * 触发文件选择框点击事件
 */
function triggerFileInput() {
  fileInput.value.click();
}

/**
 * 处理文件上传事件
 * @param {Event} e - 文件选择事件对象
 */
function handleFileUpload(e) {
  const files = Array.from(e.target.files);
  files.forEach(file => {
    const reader = new FileReader();
    reader.onload = ev => {
      mediaList.value.push({ file, preview: ev.target.result, type: file.type.startsWith('video') ? 'video' : 'image' });
    };
    reader.readAsDataURL(file);
  });
}

/**
 * 移除指定索引的媒体项
 * @param {number} idx - 要移除的媒体项索引
 */
function removeMedia(idx) {
  mediaList.value.splice(idx, 1);
}

/**
 * 切换可见性菜单显示状态
 */
function toggleVisibilityMenu() {
  showVisibilityMenu.value = !showVisibilityMenu.value;
}

/**
 * 选择可见性选项并关闭菜单
 * @param {number} value - 可见性值（0: 所有人可见, 1: 好友可见, 2: 仅自己可见）
 */
function selectVisibility(value) {
  visibility.value = value;
  showVisibilityMenu.value = false;
}

/**
 * 提交编辑内容
 */
async function submitEdit() {
  if (!content.value && !mediaList.value.length) return;
  isLoading.value = true;
  try {
    const uploadedUrls = [];
    for (const media of mediaList.value) {
      if (media.file) {
        const formData = new FormData();
        formData.append('file', media.file);
        const response = await axios.post('/activity/upload', formData);
        uploadedUrls.push(response.data); // 七牛云外链
      } else {
        uploadedUrls.push(media.preview);
      }
    }

    // 判断话题是否发生变化
    const oldTopicId = props.activity.topicId;
    const newTopicId = selectedTopicId.value;

    const data = {
      ...props.activity,
      content: content.value,
      mediaUrls: JSON.stringify(uploadedUrls),
      visibility: visibility.value,
      topicId: newTopicId
    };
    await axios.put(`/activity/${props.activity.id}`, data);

    // 处理话题计数变化
    if (oldTopicId !== newTopicId) {
      // 减少旧话题计数
      if (oldTopicId) {
        try {
          await axios.post(`http://localhost:8085/topics/${oldTopicId}/decrement`);
        } catch (e) {
          console.error('减少旧话题计数失败:', e);
        }
      }

      // 增加新话题计数
      if (newTopicId) {
        try {
          await axios.post(`http://localhost:8085/topics/${newTopicId}/increment`);
        } catch (e) {
          console.error('增加新话题计数失败:', e);
        }
      }
    }

    // 强制刷新 - 清除缓存并重新加载
    emit('success', { refresh: true });
    emit('close');

    // 添加额外的刷新机制
    setTimeout(() => {
      window.location.reload(); // 强制页面刷新
    }, 1000);
  } catch (e) {
    alert('保存失败');
  } finally {
    isLoading.value = false;
  }
}

/**
 * 创建新话题
 */
async function createTopic() {
  if (!newTopicContent.value.trim()) return;
  isCreatingTopic.value = true;
  try {
    await axios.post('http://localhost:8085/topics', { content: newTopicContent.value });
    const topicRes = await axios.get('http://localhost:8085/topics');
    topics.value = topicRes.data;
    const created = topics.value.find(t => t.content === newTopicContent.value);
    if (created) selectedTopicId.value = created.id;
    showNewTopicModal.value = false;
    newTopicContent.value = '';
  } catch (e) {
    alert('新建话题失败');
  } finally {
    isCreatingTopic.value = false;
  }
}

/**
 * 监听 mediaList 变化，自动滚动到最新添加的媒体项
 */
watch(mediaList, async () => {
  await nextTick();
  if (mediaPreview.value) {
    mediaPreview.value.scrollTop = mediaPreview.value.scrollHeight;
  }
}, { deep: true });
</script>


<style scoped>
.activity-post-editor {
  background: #fff;
  padding: 32px 40px 28px 40px;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(44,62,80,0.13);
  width: 100%;
  max-width: 600px;
  box-sizing: border-box;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
  height: auto;
  max-height: 90vh;
  overflow-y: auto;
  overflow-x: hidden;
}
.editor-textarea {
  width: 100%;
  min-height: 80px;
  max-height: 220px;
  background: #f8f9fa;
  color: #23232b;
  border-radius: 10px;
  border: 1.5px solid #e0e0e0;
  padding: 16px 18px;
  font-size: 17px;
  line-height: 1.8;
  resize: vertical;
  margin-bottom: 18px;
  box-sizing: border-box;
  overflow-y: auto;
  transition: border 0.2s, background 0.2s;
}
.editor-textarea:focus {
  border: 1.5px solid #3498db;
  background: #f5f6fa;
  outline: none;
}
.editor-textarea::placeholder {
  color: #bfc3c9;
  font-size: 16px;
}
.row-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  margin-bottom: 18px;
}
.media-upload-plus {
  width: 90px;
  height: 90px;
  background: #fafbfc;
  border-radius: 14px;
  border: 1.5px solid #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
  box-shadow: 0 1px 4px rgba(44,62,80,0.04);
  flex-shrink: 0;
}
.media-upload-plus:hover {
  border: 1.5px solid #3498db;
  background: #f0f6ff;
  box-shadow: 0 2px 8px rgba(52,152,219,0.10);
}
.plus-icon {
  font-size: 38px;
  color: #c3c8d1;
  font-weight: 400;
  user-select: none;
}
.visibility-selector {
  min-width: 160px;
  max-width: 220px;
  flex: 1;
  margin-bottom: 0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.selected-visibility {
  min-width: 140px;
  max-width: 220px;
  width: 100%;
  height: 48px;
  box-sizing: border-box;
  border: 1px solid #e0e0e0;
  border-radius: 14px;
  padding: 0 18px;
  background: #fafbfc;
  color: #23232b;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 17px;
  margin-bottom: 0;
  transition: border 0.2s, background 0.2s;
  position: relative;
}
.selected-visibility i.fas.fa-chevron-down {
  margin-left: auto;
  font-size: 15px;
  color: #bfc3c9;
}
.selected-visibility:hover, .selected-visibility:focus {
  border: 1px solid #bfc3c9;
  background: #f5f6fa;
}
.visibility-menu {
  min-width: 140px;
  max-width: 220px;
  right: auto;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  position: absolute;
  border: 1px solid #e0e0e0;
  border-radius: 16px;
  background: #fff;
  margin-top: 6px;
  box-shadow: 0 8px 32px rgba(44,62,80,0.10);
  overflow: hidden;
  z-index: 10;
}
.visibility-option {
  color: #23232b !important;
  padding: 14px 20px;
  cursor: pointer;
  border-radius: 0;
  font-size: 17px;
  transition: background 0.2s, color 0.2s;
  text-align: left;
  background: #fff;
}
.visibility-option.active, .visibility-option:hover {
  color: #23232b !important;
  background: #f5f6fa;
  font-weight: bold;
}
.black-btn, .publish-btn-bottom {
  background: linear-gradient(135deg, #43484e, #23272b);
  color: #fff;
  border: none;
  border-radius: 18px;
  box-shadow: 0 4px 16px rgba(52,152,219,0.10);
  font-size: 18px;
  font-weight: 500;
  padding: 14px 0;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  margin-bottom: 18px;
  transition: background 0.2s, box-shadow 0.2s;
}
.black-btn:disabled, .publish-btn-bottom:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #ccc;
}
.black-btn:not(:disabled):hover, .publish-btn-bottom:not(:disabled):hover {
  background: linear-gradient(135deg, #23272b, #43484e);
  box-shadow: 0 6px 24px rgba(52,152,219,0.16);
}
.media-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 8px;
  max-height: 272px; /* 两排图片+间距 */
  overflow-y: auto;
  /* 滚动条白色风格 */
  scrollbar-width: thin;
  scrollbar-color: #e0e0e0 #fff;
}
.media-preview::-webkit-scrollbar {
  width: 8px;
  background: #fff;
  border-radius: 8px;
}
.media-preview::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 8px;
}
.media-thumb {
  flex: 0 0 calc((100% - 24px) / 3);
  max-width: calc((100% - 24px) / 3);
  box-sizing: border-box;
  margin-bottom: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.media-thumb img, .media-thumb video {
  width: 100%;
  max-width: 120px;
  max-height: 120px;
  min-width: 0;
  min-height: 0;
  aspect-ratio: 1 / 1;
  height: auto;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(44,62,80,0.10);
  object-fit: cover;
  display: block;
}
.remove-btn {
  margin-top: 12px;
}
@media (max-width: 600px) {
  .media-thumb {
    flex: 0 0 calc((100% - 12px) / 2);
    max-width: calc((100% - 12px) / 2);
  }
}
.activity-actions {
  display: flex;
  gap: 32px;
  align-items: center;
  margin-top: 4px;
  justify-content: flex-end;
}
.action-group {
  display: flex;
  align-items: center;
  font-size: 18px;
  gap: 6px;
  user-select: none;
}
.comment-action {
  color: #19a6f7;
}
.like-action {
  color: #bfc3c9;
}
.action-num {
  font-size: 16px;
  margin-left: 2px;
}
.close-modal-btn {
  margin-bottom: 36px !important;
}
.topic-selector {
  width: 100%;
  margin-bottom: 12px;
}
.topic-select {
  width: 100%;
  padding: 10px 14px;
  border-radius: 10px;
  border: 1.5px solid #e0e0e0;
  font-size: 16px;
  background: #fafbfc;
  color: #23232b;
  margin-bottom: 0;
  box-sizing: border-box;
}
.new-topic-modal {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 10;
  transform: translate(-50%, -50%);
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(44,62,80,0.13);
  padding: 32px 32px 18px 32px;
  min-width: 320px;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.topic-input {
  width: 100%;
  padding: 12px 14px;
  border-radius: 10px;
  border: 1.5px solid #e0e0e0;
  font-size: 16px;
  background: #fafbfc;
  color: #23232b;
  margin-bottom: 0;
  box-sizing: border-box;
}
.close-modal-btn {
  margin-bottom: 18px !important;
  background: none;
  border: none;
  color: #b0b3c6;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 6px;
  padding: 4px 10px;
  transition: background 0.2s, color 0.2s;
}
.close-modal-btn:hover {
  background: #f0f2f5;
  color: #3498db;
}
.black-btn {
  background: linear-gradient(135deg, #43484e, #23272b);
  color: #fff;
  border: none;
  border-radius: 18px;
  box-shadow: 0 4px 16px rgba(52,152,219,0.10);
  font-size: 18px;
  font-weight: 500;
  padding: 14px 0;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  margin-bottom: 0;
  transition: background 0.2s, box-shadow 0.2s;
}
.black-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #ccc;
}
.black-btn:not(:disabled):hover {
  background: linear-gradient(135deg, #23272b, #43484e);
  box-shadow: 0 6px 24px rgba(52,152,219,0.16);
}
</style> 